package com.aijia.custom.product.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aijia.custom.product.R;
import com.aijia.custom.product.adapter.ArtItemAdapter;
import com.aijia.custom.product.customview.CustomDialog;
import com.aijia.custom.product.customview.LoadingWaitDialog;
import com.aijia.custom.product.customview.NoDoubleClickListener;
import com.aijia.custom.product.data.ArtItemData;
import com.aijia.custom.product.data.WSArtDetailData;
import com.aijia.custom.product.listener.IWSheetArtDetailListener;
import com.aijia.custom.product.listener.IWSheetArtFinishListener;
import com.aijia.custom.product.manager.WSheetArtDetailManager;
import com.aijia.custom.product.manager.WSheetArtFinishManager;
import com.aijia.custom.product.utils.ArtStatusHelper;
import com.aijia.custom.product.utils.DateUtils;
import com.aijia.custom.product.utils.Notification;
import com.aijia.custom.product.utils.SharedPreferencesUtils;
import com.powerfulrecyclerview.listener.OnRefreshListener;

import java.util.ArrayList;


/**
 * 单步工序详情
 * Created by yejianjun on 2019/1/19.
 */

public class WSheetArtDetailActvity extends Activity implements View.OnClickListener, OnRefreshListener, ArtItemAdapter.OnItemClickListener, IWSheetArtDetailListener, IWSheetArtFinishListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;


    private TextView titleTV;

    private Button mySelfBtn, partBtn, allBtn;
    private int _id;
    private String title;
    /**
     * 待处理
     */
    private final int STATUS_INIT = 1;
    /**
     * 进行中
     */
    private final int STATUS_PART = 2;
    /**
     * 全部完成
     */
    private final int STATUS_ALL = 3;
    /**
     * 自己跟踪
     */
    private final int STATUS_mySELf = 4;
    private Dialog customDialog;
    private ArtItemAdapter adapter;
    private int staffId;
    // 已经完成数量
    private int alreadyAmount;
    // 下单总数量
    private int pAmuout;
    private TextView refreshTV;
    private ImageButton backBtn;
    private Dialog pDialog;

    private ListView listView;

    private int finish_status = STATUS_INIT;
    private WSheetArtDetailManager manager;
    private WSheetArtFinishManager finishManager;
    private TextView staffNameTV, statusTV;
    private int wsheetId;
    private int type = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wsheet_art_detail);

        title = getIntent().getStringExtra("wsheet_art_detail_title");
        staffId = getIntent().getIntExtra("staff_id", 0);
        wsheetId = getIntent().getIntExtra("wsheet_id", 0);
        _id = getIntent().getIntExtra("wsheet_art_detail_id", 0);
        initWattingView();
        init();
        initManger();
        reqData();
    }

    private void init() {
        titleTV = findViewById(R.id.title_tv);
        titleTV.setText(title);
        backBtn = findViewById(R.id.left_imageButton);
        backBtn.setVisibility(View.VISIBLE);
        backBtn.setOnClickListener(noDoubleClickListener);

        staffNameTV = findViewById(R.id.wsheet_art_detail_staffName);
        statusTV = findViewById(R.id.wsheet_art_detail_status);

        mySelfBtn = findViewById(R.id.half_btn);
        partBtn = findViewById(R.id.part_in_btn);
        allBtn = findViewById(R.id.complete_btn);
        //
        if (title.equals("网店定金")) {
            mySelfBtn.setVisibility(View.VISIBLE);
        } else {
            mySelfBtn.setVisibility(View.GONE);
        }

        mySelfBtn.setOnClickListener(noDoubleClickListener);
        partBtn.setOnClickListener(noDoubleClickListener);
        allBtn.setOnClickListener(noDoubleClickListener);

        listView = findViewById(R.id.wsheet_art_detail_listview);

        adapter = new ArtItemAdapter(this, type);
        adapter.setOnItemClickListener(this);
        listView.setAdapter(adapter);

    }

    NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            // 先判断用户类型 再判断工序ID是否一致
            int userType = SharedPreferencesUtils.getUserType(WSheetArtDetailActvity.this);
            int userId = SharedPreferencesUtils.getUserID(WSheetArtDetailActvity.this);
            switch (v.getId()) {
                case R.id.part_in_btn:

                    if (staffId == userId) {
                        showInputDialog("进行中", 2);
                    } else {
                        Notification.toast(WSheetArtDetailActvity.this, "无权限完成此操作");
                        return;
                    }

                    break;

                case R.id.complete_btn:
                    if (staffId == userId) {
                        showInputDialog("确认完成吗？", 3);
                    } else {
                        Notification.toast(WSheetArtDetailActvity.this, "无权限完成此操作");
                        return;
                    }
                    break;
                case R.id.right_text_tv:
                    showDialog();
                    reqData();
                    break;
                case R.id.left_imageButton:
                    finish();
                    break;
                case R.id.half_btn:
                    // 自己跟踪  --- 确认是否自己跟踪
                    if (staffId == userId) {
                        showInputDialog("确认自己跟踪吗？", 4);
                    } else {
                        Notification.toast(WSheetArtDetailActvity.this, "无权限完成此操作");
                        return;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void initManger() {
        manager = new WSheetArtDetailManager(this);
        manager.addWSheetArtDetailListener(this);
        finishManager = new WSheetArtFinishManager(this);
        finishManager.addWSheetArtFinishListener(this);
    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
    }

    private void reqData() {
        manager.wSheetArtDetail(_id);
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * @param title
     * @param status 1： 取消 2： 进行中 3： 完成 4：自己跟踪
     */
    private void showInputDialog(String title, final int status) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        customDialog = new Dialog(this, R.style.custom_Dialog);
        View layout = inflater.inflate(R.layout.custom_input_dialog, null);
        TextView titleTV = layout.findViewById(R.id.title);
        titleTV.setText(title);
        final EditText amount = layout.findViewById(R.id.complete_count_et);
        final EditText content = layout.findViewById(R.id.complete_remark_et);
        amount.setVisibility(View.GONE);
        (layout.findViewById(R.id.confirmBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.dismiss();
                if (TextUtils.isEmpty(content.getText().toString())) {
                    Notification.toast(WSheetArtDetailActvity.this, "备注不能为空");
                    return;
                }
                showDialog();
                finishManager.wSheetArtFinish(_id, content.getText().toString().trim(), status);
            }
        });
        (layout.findViewById(R.id.cancelBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.dismiss();
            }
        });
        customDialog.setContentView(layout);
        customDialog.show();
    }


    private void display(WSArtDetailData data) {

    }

    @Override
    public void onRefresh() {

    }

    private void showDialog() {
        pDialog = LoadingWaitDialog.createLoadingDialog(this, "等待中...");
        pDialog.show();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager)
            manager.removeWSheetArtDetailListener(this);
        if (null != finishManager)
            finishManager.removeWSheetArtFinishListener(this);
    }

    @Override
    public void itemClick(View v) {
        final int position;
        switch (v.getId()) {
            case R.id.wsheet_art_item_delete:
                position = (Integer) v.getTag(R.id.wsheet_art_item_delete);
                CustomDialog.Builder builder = new CustomDialog.Builder(this);
                builder.setTitle("确认删除该条记录吗？");
                builder.setPositiveButton(getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
//                                delManager.wSheetArtItemDel(adapter.getList().get(position).getId());

                                alreadyAmount -= adapter.getList().get(position).getAmount();
//                                amountTV.setText("数量：" + alreadyAmount);
                                if (alreadyAmount >= pAmuout) {
                                    finish_status = STATUS_ALL;
                                } else if (alreadyAmount > 0) {
                                    finish_status = STATUS_PART;
                                } else if (alreadyAmount == 0) {
                                    finish_status = STATUS_INIT;
                                }

                                if (STATUS_ALL == finish_status) {
                                    // 如果是全部完成，按钮不可点击...
                                    partBtn.setBackgroundResource(R.drawable.shape_receangle_gray);
                                    allBtn.setBackgroundResource(R.drawable.shape_receangle_gray);
                                    partBtn.setClickable(false);
                                    allBtn.setClickable(false);
//                                    statusTV.setText("状态：全部完成");
                                } else if (STATUS_PART == finish_status) {
//                                    statusTV.setText("状态：部分完成");
                                    partBtn.setBackgroundResource(R.drawable.shape_yellow);
                                    allBtn.setBackgroundResource(R.drawable.shape_receangle_red);
                                    partBtn.setClickable(true);
                                    allBtn.setClickable(true);
                                } else if (STATUS_INIT == finish_status) {
//                                    statusTV.setText("状态：未完成");
                                    partBtn.setBackgroundResource(R.drawable.shape_yellow);
                                    allBtn.setBackgroundResource(R.drawable.shape_receangle_red);
                                    partBtn.setClickable(true);
                                    allBtn.setClickable(true);
                                }

//                                ArtStatusHelper.getInstance().updateStatus(wsheetId, _id, finish_status, DateUtils.getCurrentDate());

                                // 删除该条记录 并刷新
                                adapter.removeOneData(position);
                                adapter.notifyDataSetChanged();

                            }
                        });
                builder.setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            default:
                break;
        }
    }


    @Override
    public void onWSheetArtFinishFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        Notification.toast(this, errorMsg);
    }

    @Override
    public void onWSheetArtFinishSuccess(ArtItemData itemData) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        // 成功
        // 列表数据更新一条
        adapter.addOneData(itemData);
        adapter.notifyDataSetChanged();

        changeStatus(itemData.getStatus());

        ArtStatusHelper.getInstance().updateStatus(wsheetId, _id, itemData.getStatus(), DateUtils.getCurrentDate());

        // 如果是网店定金 更新到最外出状态显示
        if (title.equals("网店定金")) {
            ArtStatusHelper.getInstance().updateListStatus(wsheetId, itemData.getStatus());
        }
    }

    @Override
    public void onWSheetArtDetailFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        waittingLayout.setVisibility(View.VISIBLE);
        waittingProBar.setVisibility(View.GONE);
        waittingTV.setText(errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onWSheetArtDetailSuccess(WSArtDetailData data) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        waittingLayout.setVisibility(View.GONE);
        staffNameTV.setText("责任人：" + (data.getStaffName() == null ? "" : data.getStaffName()));
        changeStatus(data.getStatus());

        adapter.setData(data.getItems());
        adapter.notifyDataSetChanged();
    }

    private void changeStatus(int status) {
        if (status == STATUS_PART) {
            statusTV.setText("状态：进行中");
            mySelfBtn.setClickable(true);
            mySelfBtn.setFocusable(true);
            partBtn.setClickable(true);
            partBtn.setFocusable(true);
            allBtn.setClickable(true);
            allBtn.setFocusable(true);
        } else if (status == STATUS_ALL) {
            statusTV.setText("状态：已完成");
            mySelfBtn.setClickable(false);
            mySelfBtn.setFocusable(false);
            partBtn.setClickable(false);
            partBtn.setFocusable(false);
            allBtn.setClickable(false);
            allBtn.setFocusable(false);
            mySelfBtn.setBackgroundResource(R.drawable.shape_receangle_gray);
            partBtn.setBackgroundResource(R.drawable.shape_receangle_gray);
            allBtn.setBackgroundResource(R.drawable.shape_receangle_gray);
        } else if (status == STATUS_INIT) {
            statusTV.setText("状态：待处理");
            mySelfBtn.setClickable(true);
            mySelfBtn.setFocusable(true);
            partBtn.setClickable(true);
            partBtn.setFocusable(true);
            allBtn.setClickable(true);
            allBtn.setFocusable(true);
        } else if (status == STATUS_mySELf) {
            statusTV.setText("状态：自己跟踪");
            mySelfBtn.setClickable(true);
            mySelfBtn.setFocusable(true);
            partBtn.setClickable(true);
            partBtn.setFocusable(true);
            allBtn.setClickable(true);
            allBtn.setFocusable(true);
        }
    }

    /*private void showSelfDialog() {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("确认自己跟踪吗？");
        builder.setPositiveButton(this.getResources().getString(R.string.confirm),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finishManager.wSheetArtFinish(_id, "", status);
                    }
                });
        builder.setNegativeButton(this.getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }*/


}
